package top.eggcode.system.modules.user.store;

import org.springframework.stereotype.Repository;
import top.eggcode.common.base.JpaSimpleStore;
import top.eggcode.common.model.ListPage;
import top.eggcode.plugins.query.CriteriaBuilder;
import top.eggcode.system.modules.user.model.AccountEntity;
import top.eggcode.system.modules.user.model.UserQuery;

import javax.annotation.Resource;
import javax.persistence.EntityManager;
import java.util.Optional;

/**
 * Title:
 * Description: TODO
 * Date: 2021/8/15 21:50
 *
 * @author JiaQi Ding
 * @version 1.0
 */
@Repository
public class AccountStore extends JpaSimpleStore<AccountEntity, String> {


    @Resource
    private CriteriaBuilder builder;

    public AccountStore(EntityManager manager) {
        super(AccountEntity.class, manager);
    }

    public ListPage<AccountEntity> listPage(UserQuery query) {
        return builder.createQuery(AccountEntity.class)
                .fromEntity("root")
                .leftJoin("system_user", "u", "root.user_id = u.id")
                .where(condition -> {
                    if (query.getNickname() != null) {
                        condition.likeAny("u.nickname", query.getNickname());
                    }
                    if (query.getSex() != null) {
                        condition.eq("u.sex", query.getSex());
                    }
                    if (query.getUsername() != null) {
                        condition.likeAny("root.username", query.getUsername());
                    }
                })
                .fetchPage(query);
    }

    /**
     * 查找一个
     *
     * @param username 用户名
     * @return 帐户
     */
    public Optional<AccountEntity> getByUsername(String username) {
        return builder.createQuery(AccountEntity.class)
                .fromEntity("root")
                .where(condition -> {
                    condition.eq("root.username", username)
                            // 未删除
                            .eq("root.deleted", 0);
                })
                .limit(1)
                .fetchAny();
    }
}
